<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >  
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                <el-divider content-position="left">基础信息</el-divider>  
                <el-row>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="培训计划名称" prop="v_TrainingPlanName">
                            <el-select 
                                filterable 
                                v-model="ruleForm.v_TrainingPlanName" 
                                placeholder="请选择培训计划" 
                                value-key='id'
                                @change="planChange"
                            >
                                <el-option
                                    v-for="item in planOption"
                                    :key="item.id"
                                    :label="item.v_CourseName"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="考题类型名称">
                            <el-select 
                                filterable
                                v-model="ruleForm.v_TypeName" 
                                placeholder="请选择考题类型" 
                                @change="typeChange"
                            >
                                <el-option
                                    v-for="item in typeOption"
                                    :key="item.n_Type"
                                    :label="item.v_TypeName"
                                    :value="item.n_Type"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="单题分数" prop="n_Score">
                            <el-input v-model="ruleForm.n_Score" type="number" placeholder="请输入单题分数" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="排序号">
                            <el-input v-model="ruleForm.n_Sort" type="number" placeholder="请输入排序号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="考题题目" prop="v_Topic">
                            <el-input v-model="ruleForm.v_Topic" placeholder="请输入题目" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="isCorrect" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="是否正确">
                            <el-switch
                                v-model="ruleForm.isTrue"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                active-text="是"
                                inactive-text="否"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <template v-if="!isCorrect">
                    <el-divider content-position="left">题目选项</el-divider>
                    <el-button @click="addHandle" icon="ele-Plus" type="primary" text style="margin-bottom: 10px;"> 新增选项 </el-button>
                    <el-table class="table-s" :data="ExaminationDBDe" style="width: 100%" border>
                        <el-table-column min-width="60" :show-overflow-tooltip="true" label="选项"  align="center">
                            <template #default="scope">
                                <el-input class="inp-s" v-model="scope.row.v_Option" placeholder="请输入选项，如：A" />
                            </template>
                        </el-table-column>
                        <el-table-column min-width="160" :show-overflow-tooltip="true" label="选项内容"  align="center">
                            <template #default="scope">
                                <el-input type="textarea" v-model="scope.row.v_Content" placeholder="请输入选项内容" />
                            </template>
                        </el-table-column>
                        <el-table-column min-width="60" prop="createdUserName" :show-overflow-tooltip="true" label="是否为正确答案"  align="center">
                            <template #default="scope">
                                <el-switch
                                    v-model="scope.row.isTrue"
                                    active-color="#07AAF9"
                                    inactive-color="#FF5F33"
                                    inline-prompt
                                    active-text="是"
                                    inactive-text="否"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column min-width="60" label="操作" align="center" fixed="right">
                            <template #default="scope">
                                <div class="operate-s">
                                    <el-button @click="deleteHandle(scope.row.inx)" class="icon-e" icon="ele-Delete" size="small" text type="danger">移除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取 消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules , ElMessage, ElMessageBox } from 'element-plus';
import { EduTrainingPlanList , OmsEduExaminationDBAdd , OmsEduExaminationDBUpdate } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    isTrue?: Boolean, // 当题型为判断题的时候（该题答案是否正确）
    l_TrainingPlanId: Number, // 培训计划id
    v_TrainingPlanName: String, // 培训计划名称（用于显示）
    n_Type: Number, // 考题类型
    v_TypeName: String, // 考题类型名称
    n_Score: Number, // 单题分数
    n_Sort: Number, // 考题排序号
    v_Topic: String, // 题目
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const planOption = ref();
        const isCorrect = ref(false);
        const ExaminationDBDe = ref();
        ExaminationDBDe.value = [
            {inx:0, l_ExaminationDBId: 0, v_Option: '', v_Content: '', isTrue: true},
        ];
        const planOptions = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        });

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 培训计划
            v_TrainingPlanName: [
				{ required: true, message: '请选择培训计划', trigger: 'change' },
			],
            // 考题题目
            v_Topic: [
				{ required: true, message: '请输入考题题目', trigger: 'blur' },
			],
            // 单题分数
            n_Score: [
				{ required: true, message: '请输入单题分数', trigger: 'blur' },
			],
        });

        /*** getPlanList 获取培训计划列表 */
        const getPlanList = async() => {
            let param = {};
            let res:any = await EduTrainingPlanList(param);
            if(res.success) planOption.value = res.data;
        };

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        };

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        };

        /*** verifyFun 验证事件 */
        const verifyFun = (arr: any) => {
            let isJump = true;
            if(isJump){
                arr.map((item:any) => {
                    if(item.v_Option.trim() === '' || item.v_Content.trim() === ''){
                        isJump = false
                    }
                    return
                })
            }
            return isJump;
        };

        /*** correctFun 验证正确函数 */
        const correctFun = (arr: any) => {
            let isCorrect = false;
            if (arr.some((item:any) => item.isTrue)) {
                isCorrect = true;
            }
            return isCorrect;
        };

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param:any = toRaw(state.ruleForm)
                    let setExaminationDBDe = [];
                    if(!isCorrect.value){
                       let getState = verifyFun(ExaminationDBDe.value)
                       if(!getState){
                            ElMessage({
                                type: 'warning',
                                message: '有选项或选项内容为完善，请检查完善',
                                duration: 1500
                            });
                            return
                       }else{
                            let getCorrect:any = correctFun(ExaminationDBDe.value);
                            if(!getCorrect){
                                ElMessage({
                                    type: 'warning',
                                    message: '选项内容最少需要有一个是正确的答案',
                                    duration: 1500
                                });
                                return
                            }
                       }
                    }else{
                        let setObj = {
                            l_ExaminationDBId: 0,
                            v_Option: '',
                            v_Content: param.v_Topic,
                            isTrue: param.isTrue,
                        }
                        setExaminationDBDe.push(setObj)
                    }
                    if(!isCorrect.value) param.ExaminationDBDe = toRaw(ExaminationDBDe.value);
                    else param.ExaminationDBDe = setExaminationDBDe;
                    state.repeatDis = true;
                    try{
                        let res: any;
                        if(props.repairInfo !== ''){
                            res = await OmsEduExaminationDBUpdate(param);
                        }else{
                            res = await OmsEduExaminationDBAdd(param);
                        }
                        if(res.success){
                            ctx.emit('updateData');
                            ctx.emit('controlUseClick' , state.ruleForm.l_TrainingPlanId);
                            state.repeatDis = false;
                        }else{ 
                            state.repeatDis = false; 
                            ctx.emit('controlUseClick' , state.ruleForm.l_TrainingPlanId);
                        }
                    }catch(error){state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        };

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        };

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                getPlanList(); // 获取培训计划下拉框列表
                // 状态数据重置
                isCorrect.value = false;
                state.repeatDis = false;
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    let getData = JSON.parse(props.repairInfo);
                    if(getData.n_Type === 2){
                        isCorrect.value = true;
                        getData.isTrue = getData.options[0].isTrue;
                    }else{
                        getData.options.map((item: any, index: any) => {
                            item.inx = index
                        });
                        ExaminationDBDe.value = getData.options;
                    }
                    state.ruleForm = getData;
                }else{
                    titleCon.value = '新增';
                    ExaminationDBDe.value = [
                        {inx:0, l_ExaminationDBId: 0, v_Option: '', v_Content: '', isTrue: true},
                    ];
                    state.ruleForm = {
                        l_TrainingPlanId: 0, // 培训计划id
                        v_TrainingPlanName:'', // 培训计划名称（用于显示）
                        n_Type: 0, // 考题类型
                        v_TypeName: '单选题', // 考题类型名称
                        n_Score: 0, // 单题分数
                        n_Sort: 0, // 考题排序号
                        v_Topic: '', // 题目
                        isTrue: true, // 当题型为判断题的时候（该题答案是否正确）
                    }
                }
            }
        });

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        });

        /*** planChange 培训计划选择事件 */
        const planChange = (val:any) => {
            console.log(val,'培训计划')
            state.ruleForm.v_TrainingPlanName = val.v_CourseName;
            state.ruleForm.l_TrainingPlanId = val.id;
        };

        /*** typeChange 考题类型选择事件 */
        const typeChange = (val:any) => {
            state.ruleForm.n_Type = val;
            if(val === 2){
                isCorrect.value = true;
            }else{
                isCorrect.value = false;
            }
        };

        /*** addHandle 新增选项 */
        const addHandle = () => {
            let len = ExaminationDBDe.value.length;
            let setData = {
                inx:len, l_ExaminationDBId: 0, v_Option: '', v_Content: '', isTrue: false
            }
            ExaminationDBDe.value.push(setData);
        };

        /*** deleteHandle 移除选项 */
        const deleteHandle = (val:any) => {
            let len = ExaminationDBDe.value.length;
            if(len === 1){
                ElMessage({
                    type: 'error',
                    message: '基础数据不能移除',
                });
            }else{
                ElMessageBox.confirm('请确定移除此条数据？','提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                .then(async() => {
                    ExaminationDBDe.value = ExaminationDBDe.value.filter((item:any) => item.inx !== val);
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '已取消',
                    })
                });
            }
        };

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            planChange,
            planOption,
            typeChange,
            typeOption: [
                {v_TypeName: '单选题', n_Type: 0},
                {v_TypeName: '多选题', n_Type: 1},
                {v_TypeName: '判断题', n_Type: 2}
            ],
            ExaminationDBDe,
            addHandle,
            deleteHandle,
            isCorrect,
            planOptions,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%!important;
    }
    :deep(.el-input){
        width: 100%;
    }
    .inp-s{
        :deep(.el-input__inner){
            text-align: center;
        }
    }
</style>